package leetcode.simple._13;

import leetcode.dynamic_programming.Rob;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mgl
 * @version 1.0
 * @description TODO
 * @date 2023/9/28 15:23
 */
public class RomanToInt {

    public int romanToInt_old(String s) {
        char[] array = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int result = 0;

        for (int i = 0; i < array.length; ) {
            if (array[i] == 'I' && i + 1 < array.length && array[i + 1] == 'V') {
                result += 4;
                i += 2;
            } else if (array[i] == 'I' && i + 1 < array.length && array[i + 1] == 'X') {
                result += 9;
                i += 2;
            } else if (array[i] == 'X' && i + 1 < array.length && array[i + 1] == 'L') {
                result += 40;
                i += 2;
            } else if (array[i] == 'X' && i + 1 < array.length && array[i + 1] == 'C') {
                result += 90;
                i += 2;
            } else if (array[i] == 'C' && i + 1 < array.length && array[i + 1] == 'D') {
                result += 400;
                i += 2;
            } else if (array[i] == 'C' && i + 1 < array.length && array[i + 1] == 'M') {
                result += 900;
                i += 2;
            } else {
                result += map.get(array[i]);
                i++;
            }
        }

        return result;
    }

    public int romanToInt(String s) {
        int sum = 0;
        int pre = mapping(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            int num = mapping(s.charAt(i));
            if (pre < num) {
                sum -= pre;
            }else {
                sum += pre;
            }
            pre = num;
        }
        sum += pre;
        return sum;
    }

    private int mapping(char c) {
        switch (c){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }

    public static void main(String[] args) {
        System.out.println(new RomanToInt().romanToInt("MCMXCIV"));
    }
}
